﻿using System.Net;
using System.Net.Sockets;
using System.Text;

//使用socket类发送udp消息
//Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//client.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6000));
//Thread t = new Thread(() => sendMsg(client));
//t.Start();
//Thread t2 = new Thread(() => receiveMsg(client));
//t2.Start();
//Console.WriteLine("客户端已经开启");

//void receiveMsg(Socket client)
//{
//    EndPoint point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6001);
//    while (true)
//    {
//        byte[] buffer = new byte[1024];
//        int length = client.ReceiveFrom(buffer, ref point);
//        var msg = Encoding.UTF8.GetString(buffer, 0, length);
//        Console.WriteLine($"收到了消息:{msg}");
//    }
//}

//void sendMsg(Socket client)
//{
//    EndPoint point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6001);
//    while (true)
//    {
//        var msg = Console.ReadLine();
//        client.SendTo(Encoding.UTF8.GetBytes(msg), point);
//    }
//}

//使用udpclient发送消息
UdpClient udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9301));
Console.WriteLine("udp客户端已开启");

Thread t = new Thread(() => ReciveMsg(udpClient));
t.Start();

Thread t2 = new Thread(() => SendMsg(udpClient));
t2.Start();

void SendMsg(UdpClient udpClient)
{
    while (true)
    {
        IPEndPoint point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9300);
        var message = Console.ReadLine();
        var data = Encoding.UTF8.GetBytes(message);
        udpClient.Send(data, data.Length, point);
    }
}




void ReciveMsg(UdpClient udpClient)
{
    while (true)
    {
        IPEndPoint point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9300);
        var data = udpClient.Receive(ref point);
        string message = Encoding.UTF8.GetString(data, 0, data.Length);
        Console.WriteLine($"接收了消息:{message}");
    }
}